﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParticleHandle : MonoBehaviour {
    public enum PrefabType {
        Chocolate,
        Colorful,
    }

    public PrefabType type;
    public ParticleSystem part;
    public List<ParticleCollisionEvent> collisionEvents;

    string[] _texturePaths = new string[] {
        CakeShopResPath.TEX_COLORFUL_GREEN,
        CakeShopResPath.TEX_COLORFUL_HUANGLV,
        CakeShopResPath.TEX_COLORFUL_ORANGE,
        CakeShopResPath.TEX_COLORFUL_QIANHUANGBAI,
        CakeShopResPath.TEX_COLORFUL_RED,
        CakeShopResPath.TEX_COLORFUL_WHITE,
        CakeShopResPath.TEX_COLORFUL_YELLOW
    };

    static Material[] _mats;

    Transform _thisTransform;

    void Start() {
        if (part == null) {
            part = GetComponent<ParticleSystem>();
        }

        collisionEvents = new List<ParticleCollisionEvent>();
        _thisTransform = transform;

        if (_mats == null || _mats.Length < 1) {
            _mats = new Material[_texturePaths.Length];

            for (var i = 0; i < _mats.Length; i++) {
                _mats[i] = new Material(Shader.Find("Unlit/Texture"));
                _mats[i].mainTexture = CommonUtility.LoadTexture(_texturePaths[i]);
            }
        }
    }

    void OnParticleCollision(GameObject other) {
        int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents);
        int i = 0;

        // 同种类型不重复生成
        if (other.transform.parent.name.Contains(type.ToString())) {
            return;
        }

        Transform t = null;

        switch (type) {
            case PrefabType.Chocolate:
                t = CommonUtility.InstantiateFrom(CakeShopResPath.PARTICLE_CHOCOLATE, other.transform);
                break;
            case PrefabType.Colorful:
                t = CommonUtility.InstantiateFrom(CakeShopResPath.PARTICLE_COLORFUL, other.transform);
                var index = Random.Range(0, _texturePaths.Length);
                t.GetComponentInChildren<Renderer>().material = _mats[index];
                break;
        }

        Vector3 position = collisionEvents[i].intersection;
        Vector3 forward = collisionEvents[i].normal;

        // 先删除不同种类型再创建
        if (!other.name.Contains("MiCai") && !other.transform.parent.name.Contains(type.ToString())) {
            if (!other.name.Equals("Plane")) {
                Destroy(other.transform.parent.gameObject);
                position = other.transform.position;
                forward = other.transform.forward;
            }
        }

        t.position = position;
        t.forward = forward;
        t.localEulerAngles += Vector3.forward * Random.Range(0f, 360f);
        i++;
    }

}
